package com.atguigu.redis7.double_write_consistency;

import cn.hutool.core.util.BooleanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class LockUtil {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private boolean tryLock(String key) {
        return tryLock(key, 10L, TimeUnit.SECONDS);
    }


    private boolean tryLock(String key,Long timeOut,TimeUnit timeUnit) {
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", timeOut, timeUnit);
        //避免返回值为null，我们这里使用了BooleanUtil工具类
        return BooleanUtil.isTrue(flag);
    }


    private void unlock(String key) {
        stringRedisTemplate.delete(key);
    }
}
